package com.wtwd.wtwddevice.listener.deviceServerMsg.handler.impl;

import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.AnswerStateEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.listener.deviceServerMsg.handler.IMsgHandler;
import com.wtwd.wtwddevice.model.entity.ReportSos;
import com.wtwd.wtwddevice.mq.PushMsgService;
import com.wtwd.wtwddevice.service.IDeviceService;
import com.wtwd.wtwddevice.service.IReportSosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@MsgType(MsgTypeEnum.REPORT_SOS)
public class ReportSosHandlerImpl implements IMsgHandler {
    @Resource
    private PushMsgService msgService;

    @Autowired
    private IReportSosService reportSosService;

    @Resource
    private IDeviceService deviceService;


    /**
     * sos警报记录
     * @param messageBase
     */
    @Override
    public void handleMsg(MessageBase messageBase) {
        WTProtocol wtProtocol = messageBase.getWtProtocol();
        Long deviceId = deviceService.getDeviceIdByImei(wtProtocol.getImei());

        ReportSos reportSos = new ReportSos();
        reportSos.setDeviceId(deviceId);
        reportSos.setTime(wtProtocol.getTime());
        reportSos.setNumber(wtProtocol.getNumber());
        reportSos.setCreateTime(System.currentTimeMillis());
        reportSos.setUpdateTime(System.currentTimeMillis());
        reportSosService.addReportSos(reportSos);

        wtProtocol.setTime(wtProtocol.getTime());
        wtProtocol.setBody(String.valueOf(AnswerStateEnum.NORMAL.getState()));
        wtProtocol.setBodyLength(wtProtocol.getBody().length());
        msgService.pushToDevice(messageBase.getForm(),
                MessageBase.builder().deviceKey(wtProtocol.getImei())
                        .wtProtocol(wtProtocol)
                        .build());
    }
}
